package example1;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.junit.Test;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class TestURL {
    NameValuePair nameValuePair;
    @Test
    public void t1() throws Exception {
//        String urlString = "https://www.example.com/path/page?param1=value1&param2=value2&param3=value3";
        String urlString = "https://www.baidu.com/s?wd=%E6%8A%8A%E4%BC%98%E5%8C%96%E6%B0%91%E4%BC%81%E5%8F%91%E5%B1%95%E7%8E%AF%E5%A2%83%E8%90%BD%E5%88%B0%E5%AE%9E%E5%A4%84&sa=fyb_n_homepage&rsv_dl=fyb_n_homepage&from=super&cl=3&tn=baidutop10&fr=top1000&rsv_idx=2&hisfilter=1";
//        URI uri = new URI(urlString);
//        String query = uri.getQuery();
        String query = "";
        String[] split = StringUtils.split(urlString, "?");
        if (split.length == 2) {
            query=split[1];
        }

//        List<NameValuePair> queryParams = URLEncodedUtils.parse(query, StandardCharsets.ISO_8859_1);
//        Map<String, String> paramMap = new LinkedHashMap<>();
//        for (NameValuePair param : queryParams) {
//            paramMap.put(param.getName(), param.getValue());
//        }
        Map<String, String> paramMap = parseQueryParams(query);
        System.out.println(paramMap);
    }

    private static Map<String, String> parseQueryParams(String query) {
        Map<String, String> queryParams = new LinkedHashMap<>();
        if (StringUtils.isNotBlank(query)) {
            String[] params = StringUtils.split(query, "&");
            for (String param : params) {
                String[] keyValue = StringUtils.split(param, "=");
                if (keyValue.length == 2) {
                    queryParams.put(keyValue[0], keyValue[1]);
                } else if (keyValue.length == 1) {
                    queryParams.put(keyValue[0], "");
                }
            }
        }
        return queryParams;
    }

    @Test
    public void t2() throws Exception {
        String urlString = "https://www.example.com/path/page?param1=value1&param2=value2&param3=value3";

        List<NameValuePair> queryParams = URLEncodedUtils.parse(urlString, StandardCharsets.UTF_8);
        Map<String, String> paramMap = new HashMap<>();
        for (NameValuePair param : queryParams) {
            paramMap.put(param.getName(), param.getValue());
        }

        System.out.println("Parsed query parameters:");
        for (Map.Entry<String, String> entry : paramMap.entrySet()) {
            System.out.println("Parameter: " + entry.getKey() + " = " + entry.getValue());
        }
    }
}
